import {
  ProCard,
  ProForm,
  ProFormColorPicker,
  ProFormDigit,
  ProFormGroup,
  ProFormList,
  FooterToolbar,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { useEffect, useState } from 'react';
import { editPDAConfig, getPDAConfig } from '../service';
import SpotPreview from './SpotPreview';
import { checkTimesValid, mapSpotColor, mapTimes } from './utils';

const DEFAULT_SPOTCOLOR_CONFIG: PDAColorConfig = {
  default: '#D9D9D9',
  recorded: '#73D13D',
  times: [],
  timeout: { color: '#FF4D4F', time: 30 },
};

const ColorConfigPages = (props: { ownerId: string; ifConfig: boolean }) => {
  const { ownerId, ifConfig = false } = props;
  const [form] = ProForm.useForm();
  const [prevConfig, setPrevConfig] = useState<PDAColorConfig>(DEFAULT_SPOTCOLOR_CONFIG);
  const [chillDowning, setChillDowning] = useState<number>(0);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  useEffect(() => {
    if (!ownerId) return;

    getPDAConfig(ownerId).then((res) => {
      if (!res?.success) {
        message.error({ content: '获取PDA配置失败', key: 'pda_config' });
        return;
      }
      const spotColor = mapSpotColor(res?.data?.spotColor || DEFAULT_SPOTCOLOR_CONFIG);
      form?.setFieldsValue(spotColor);

      setPrevConfig(spotColor);
    });
  }, [ownerId]);
  return (
    <ProCard>
      <ProCard colSpan="900px">
        <ProForm<PDAColorFormConfig>
          form={form}
          submitter={{
            searchConfig: {
              submitText: ifConfig ? '保存配置' : '无操作权限',
            },
            submitButtonProps: {
              disabled: !ifConfig || chillDowning > 0,
            },
            render: (_, dom) => (
              <FooterToolbar>
                <Button
                  onClick={() => {
                    if (!form) return;
                    form.validateFields();
                    const values = form.getFieldsValue();
                    const messageValid = checkTimesValid(mapTimes(values.times), values.timeout);
                    if (!messageValid.valid) {
                      message.warn({ content: messageValid.message, key: 'pda_config' });
                      return;
                    }
                    setPrevConfig(values);
                  }}
                >
                  预览
                </Button>
                {dom}
              </FooterToolbar>
            ),
          }}
          onFinish={async (values) => {
            if (!ownerId) {
              message.error({ content: '请优先选择用户', key: 'pda_config' });
              return false;
            }
            const times = mapTimes(values.times);
            const messageValid = checkTimesValid(times, values.timeout);
            if (!messageValid.valid) {
              message.warn({ content: messageValid.message, key: 'pda_config' });
              return false;
            }
            setChillDowning(5);
            const res = await editPDAConfig({
              ownerId,
              spotColor: {
                ...values,
                times,
              },
            });
            if (!res?.success) {
              message.error({ content: 'PDA配置失败', key: 'pda_config' });
              return false;
            }
            message.success({ content: 'PDA配置成功', key: 'pda_config' });
            if (res.data) {
              const spotColor = mapSpotColor(res?.data?.spotColor || DEFAULT_SPOTCOLOR_CONFIG);
              setPrevConfig(spotColor);
            }

            return true;
          }}
          initialValues={prevConfig}
        >
          <ProFormColorPicker label="空泊位颜色: " name={'default'} />
          <ProFormColorPicker label="车牌已录泊位颜色: " name={'recorded'} />
          <ProFormList
            label="分时段配置"
            name={'times'}
            min={0}
            max={5}
            creatorRecord={{
              color: '#0085fa',
              start: 0,
            }}
            creatorButtonProps={{
              creatorButtonText: '添加时段规则',
              style: {
                marginBottom: 5,
              },
            }}
            style={{
              margin: '0 auto',
              width: '100%',
            }}
            rules={[
              {
                validator: (_, values: { start: number; end: number; color: string }[]) => {
                  if (values.length === 0) {
                    return Promise.resolve();
                  }
                  for (let i = 0; i < values.length; i += 1) {
                    if (i === 0 && values[i].start !== 0) {
                      return Promise.reject(new Error('第一个时段开始时间必须为0'));
                    }
                    if (!values[i].color) {
                      return Promise.reject(new Error('颜色不能为空'));
                    }
                    if (values[i].start >= values[i].end) {
                      return Promise.reject(new Error('开始时间必须小于结束时间'));
                    }
                    if (i > 0 && values[i].start < values[i - 1].end) {
                      return Promise.reject(new Error('时段不能重叠'));
                    }
                    if (i > 0 && values[i].start !== values[i - 1].end) {
                      return Promise.reject(new Error('时段必须连续'));
                    }
                    if (i > 0 && values[i].color === values[i - 1].color) {
                      return Promise.reject(new Error('颜色不能重复'));
                    }
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ProFormGroup labelLayout="inline">
              <ProFormDigit name="start" addonAfter="分钟 " />
              <span>-</span>
              <ProFormDigit addonAfter="分钟(不包含)" name="end" />
              <ProFormColorPicker initialValue="#0085fa" addonBefore="泊位颜色：" name="color" />
            </ProFormGroup>
          </ProFormList>
          <ProFormGroup>
            <ProFormDigit addonBefore="超过 " addonAfter="分钟" name={['timeout', 'time']} />
            <ProFormColorPicker addonBefore="泊位颜色: " name={['timeout', 'color']} />
          </ProFormGroup>
        </ProForm>
      </ProCard>
      <ProCard ghost />
      <ProCard ghost bordered colSpan="500px" direction="column">
        <ProCard
          title="泊位颜色预览"
          bodyStyle={{ display: 'flex', flexWrap: 'wrap', margin: '0 auto', width: '100%' }}
        >
          <SpotPreview offline bgColor={prevConfig?.default || DEFAULT_SPOTCOLOR_CONFIG.default} />
          <SpotPreview
            arrear
            plateNumber="浙A12345"
            bgColor={prevConfig?.recorded || DEFAULT_SPOTCOLOR_CONFIG.recorded}
          />
          <SpotPreview
            member
            plateNumber="浙B12345"
            bgColor={prevConfig?.recorded || DEFAULT_SPOTCOLOR_CONFIG.recorded}
          />
          {prevConfig?.times?.map((item) => (
            <SpotPreview plateNumber="未录入" bgColor={item.color} />
          ))}
          <SpotPreview plateNumber="未录入" bgColor={prevConfig.timeout.color} />
        </ProCard>
      </ProCard>
      <ProCard ghost />
    </ProCard>
  );
};
export default ColorConfigPages;
